package com.sjr.easy.chat.app.utils;

import com.alibaba.fastjson2.JSON;
import com.sjr.easy.chat.app.EasyChatAppConfig;
import com.sjr.easy.chat.app.dto.AppTokenInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AppTokenManager {

    @Autowired
    private EasyChatAppConfig easyChatAppConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String tokenPrefix = "AppTokenPrefix_";

    public void setToken(String token, AppTokenInfo appTokenInfo) {
        String key = tokenPrefix + token;
        stringRedisTemplate.opsForValue()
                .set(key, JSON.toJSONString(appTokenInfo), easyChatAppConfig.getTokenTimeout(), TimeUnit.MILLISECONDS);
    }

    public void resetTimeout(String token) {
        String key = tokenPrefix + token;
        stringRedisTemplate
                .expire(key, easyChatAppConfig.getTokenTimeout(), TimeUnit.MILLISECONDS);
    }

    public void removeToken(String token) {
        String key = tokenPrefix + token;
        stringRedisTemplate.delete(key);
    }

    public AppTokenInfo getTokenInfo(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String key = tokenPrefix + token;
        String tokenJsonStr = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(tokenJsonStr)) {
            return null;
        }
        return JSON.parseObject(tokenJsonStr, AppTokenInfo.class);
    }

    public AppTokenInfo getTokenInfo() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        return getTokenInfo(token);
    }
}
